"""
Distributed optimization example
********************************

This example shows how to get started with Playdoh optimization. You use playdoh.maximize
to maximize a function accross your different CPUs if you have a multicore machine.
"""

"""
Gaussian function
"""
from numpy import *
"""
different functions used to compare the performance of evolutionary algo
"""
test_fun=5  #1: sphere, 2:schwefel, 3:Rastrigin, 4:Rosenbrock 5:Ackley

if test_fun==1:
#sphere  
    def fun(x1,x2,x3,x4,x5):
        return x1**2+x2**2+x3**2+x4**2+x5**2
    min_dom=-5.12
    max_dom=5.12

if test_fun==2:
##schwefel  solution  (-420.9687....)
    def fun(x1,x2,x3,x4,x5):
        return 418.9829*5+x1*sin(sqrt(abs(x1)))+x2*sin(sqrt(abs(x2)))+x3*sin(sqrt(abs(x3)))+x4*sin(sqrt(abs(x4)))+x5*sin(sqrt(abs(x5)))
    min_dom=-512.03
    max_dom=511.97

if test_fun==3:
#Rastrigin solution (0,0,0...)
    def fun(x1,x2,x3,x4,x5):
        return 10.*+x1**2-10*cos(2*pi*x1)+x2**2-10*cos(2*pi*x2)+x3**2-10*cos(2*pi*x3)+x4**2-10*cos(2*pi*x4)+x5**2-10*cos(2*pi*x5)
    min_dom=-5.12
    max_dom=5.12

if test_fun==4:
#Rosenbrock solution (1,1,1...)
    def fun(x1,x2,x3,x4,x5):
        return 100*(x2-x1**2)**2+(x1-1)**2+100*(x3-x2**2)**2+(x2-1)**2+100*(x4-x3**2)**2+(x3-1)**2+100*(x5-x4**2)**2+(x4-1)**2
    min_dom=-2.048
    max_dom=2.048
    
if test_fun==5:
#Ackley solution (0.0.0.0...)
    def fun(x1,x2,x3,x4,x5):
        return 20+exp(1)-20*exp(-0.2*sqrt(0.2*(x1**2+x2**2+x3**2+x4**2+x5**2)))
    min_dom=-2.048
    max_dom=2.048
"""

Any playdoh instruction must be called after this line
"""


if __name__ == '__main__':
    import playdoh
    from numpy import *
    from  playdoh import GA
    from  playdoh import PSO

    optinfo = dict([])

    #optinfo['FCxover']='Arithmetic'
    """
    We optimize fun with two parameters initially uniformly sampled in [-10,10].
    'results' is a dictioats['x'] and results['y'] contain the best parameters
    results['ftss'] contains the best fitness value
    """
    results = playdoh.minimize(fun, x1 = [min_dom,min_dom,max_dom,max_dom], x2 =[min_dom,min_dom,max_dom,max_dom],x3 = [min_dom,min_dom,max_dom,max_dom],x4 =[min_dom,min_dom,max_dom,max_dom],x5 =[min_dom,min_dom,max_dom,max_dom]
                               ,_optalg=GA,_verbose=True, _iterations =2,_max_cpu=2, _max_gpu=1,_group_size=5000,_optinfo=optinfo)
    
    """ 
    We print the results
    """
    playdoh.printr(results)